<template>
  <div class="consultation">
    <h2>用户管理</h2>
    <div class="flex-center">
      <el-button class="ml0" size="mini" type="primary" @click="addUser"
        >新增用户</el-button
      >
    </div>
    <div class="consultation-block">
      <div class="table" v-loading="tableLoading">
        <el-table size="mini" :data="tableData" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="phone" label="手机号"> </el-table-column>
          <el-table-column prop="nickname" label="昵称"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.phone !== 'admin'"
                type="warning"
                size="mini"
                @click="updateUser(scope.row)"
                >编辑</el-button
              >
              <el-button
                v-if="scope.row.phone !== 'admin'"
                type="primary"
                size="mini"
                @click="showCharts(scope.row)"
                >查看数据</el-button
              >
              <el-button
                type="danger"
                v-if="scope.row.phone !== 'admin'"
                size="mini"
                @click="deleteUser(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          @current-change="refreshTable"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="addForm.id ? '编辑' : '新增'"
      :visible.sync="isAddVisible"
      :close-on-click-modal="false"
      width="30%"
      :before-close="handleAddClose"
    >
      <el-form
        :model="addForm"
        status-icon
        :rules="rules2"
        size="mini"
        ref="addForm"
        label-width="100px"
      >
        <el-form-item label="手机号" prop="phone">
          <el-input :min="0" type="text" v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input type="text" v-model="addForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="text" v-model="addForm.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="btnLoading"
          @click="submitForm('addForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="健康记录"
      :visible.sync="isHealthVisible"
      width="60%"
      :before-close="handleHealthClose"
    >
      <div class="charts">
        <div class="chart" id="chart1"></div>
        <div class="chart" id="chart2"></div>
        <div class="chart" id="chart3"></div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="isHealthVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addUser, getUser, deleteUser, updateUser, getHealth } from "../service.js";
import moment from "moment";
import * as echarts from 'echarts';

export default {
  name: "home",
  mounted() {
    this.refreshTable();
  },
  data() {
    var validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else {
        const pattern = /^1[3456789]\d{9}$/;
        if (pattern.test(value)) {
          callback();
        } else {
          callback(new Error("手机号不符合规则"));
        }
      }
    };
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableLoading: false,
      isVisible: false,
      isAddVisible: false,
      dialogTitle: "",
      btnLoading: false,
      isHealthVisible: false,
      modifyForm: {
        surplus: null,
      },
      addForm: {
        phone: "",
        role: "1",
        username: "",
        surplus: "",
      },
      rules: {
        surplus: [{ required: true, message: "请输入金额", trigger: "blur" }],
      },
      rules2: {
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
        password: [{ required: true, message: '密码不能为空', trigger: "blur" }],
      },
      chartConfig: {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        yAxis: {
          type: 'value'
        },
      }
    };
  },
  methods: {
    handleClose() {
      this.isVisible = false;
    },
    handleAddClose() {
      this.isAddVisible = false;
    },
    handleHealthClose() {
      this.isHealthVisible = false;
    },
    submitForm(formName) {
      this.btnLoading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.addForm);
          if (this.addForm.id) {
            let params = JSON.parse(JSON.stringify(this.addForm))
            updateUser(params.id, params).then((res) => {
              if (res.code == 200) {
                this.$message.success("修改成功");
                this.isAddVisible = false;
                this.refreshTable();
              } else {
                this.$message.error(res.msg[0].msg);
              }
              this.btnLoading = false;
            });
          } else {
            let params = JSON.parse(JSON.stringify(this.addForm))
            addUser(params).then((res) => {
              if (res.code == 200) {
                this.$message.success("添加成功");
                this.isAddVisible = false;
                this.refreshTable();
              } else {
                this.$message.error(res.msg[0].msg);
              }
              this.btnLoading = false;
            });
          }
        }
      });
    },
    refreshTable(init = false) {
      if (init == "init") {
        this.currentPage = 1;
      }
      let params = {
        pageSize: this.pageSize,
        page: this.currentPage,
      };
      console.log(params);
      getUser(params).then((res) => {
        this.tableData = res.code === 200 ? res.data.data : [];
        this.total = res.data.total;
      });
    },
    deleteData(row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteUser(row._id).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.refreshTable();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    updateMoney(row) {
      this.currentRow = row;
      this.btnLoading = false;
      this.modifyForm.surplus = 0
      this.isVisible = true;
      this.$nextTick(() => {
        this.$refs["modifyForm"].resetFields();
      });
    },
    addUser() {
      this.addForm = {
        phone: "",
        nickname: "",
        password: "",
      }
      this.isAddVisible = true;
      this.$nextTick(() => {
        this.$refs["addForm"].resetFields();
      });
    },
    modifyS(row, index) {
      this.btnLoading = false;
      this.currentRow = row
      console.log(row, index)
      this.modifyForm = row.surplusList[index]
      this.isVisible = true;
    },
    deleteS(row, index) {
      console.log(row, index)
      this.currentRow = row
      this.$confirm('此操作将永久删除该, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let opInfo = `删除了【${row.phone}】充值记录${row.surplusList[index].surplus}`
        row.surplusList.splice(index, 1)
        updateUser(this.currentRow._id, {
          surplusList: row.surplusList,
          updator: JSON.parse(localStorage.getItem("userInfo")).username,
          opInfo
        }).then((res) => {
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.refreshTable();
          } else {
            this.$message.error(res.msg);
          }
        });
      })
    },
    deleteUser(row) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteUser(row.id).then((res) => {
          console.log(res);
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.isVisible = false;
            this.refreshTable();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    updateUser(row) {
      this.addForm = JSON.parse(JSON.stringify(row))
      this.isAddVisible = true
    },
    showCharts(row) {
      getHealth({
        date: null,
        userId: row.id
      }).then(res => {
        if (res.data.data.length == 0) {
          this.$message.error('该用户没有填写数据')
          return
        }
        this.healthList = res.data.data.sort((a, b) => {
          return moment(a.date).valueOf() - moment(b.date).valueOf();
        });
        this.isHealthVisible = true;
        this.$nextTick(() => {
          this.renderEcharts()
        })
      })
    },
    renderEcharts() {
      let chart1 = echarts.init(document.getElementById("chart1"));
      let chart2 = echarts.init(document.getElementById("chart2"));
      let chart3 = echarts.init(document.getElementById("chart3"));
      this.chartConfig = {
        ...this.chartConfig,
        xAxis: {
          data: this.healthList.map(v => v.date)
        }
      }
      chart1.setOption({
        ...this.chartConfig,
        title: {
          text: 'BMI'
        },
        series: {
          name: "BMI",
          type: 'line',
          data: this.healthList.map(v => v.bmi)
        }
      })
      
      chart2.setOption({
        ...this.chartConfig,
        title: {
          text: '血压'
        },
        series: [{
          name: "高压",
          type: 'line',
          data: this.healthList.map(v => v.pressureHigh)
        }, {
          name: "低压",
          type: 'line',
          data: this.healthList.map(v => v.pressureLow)
        }]
      })
      
      chart3.setOption({
        ...this.chartConfig,
        title: {
          text: '饮水量/ml'
        },
        series: {
          name: "饮水量/ml",
          type: 'line',
          data: this.healthList.map(v => v.urine)
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
h2 {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
.consultation-block {
  width: 90%;
  margin-left: 5%;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.edit {
  color: #409EFF;
  cursor: pointer;
}
.delete {
  color: #F56C6C;
  cursor: pointer;
}
.charts {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;

  .chart {
    width: 100%;
    height: 200px;
  }
}
</style>
